import React, { useEffect, useState } from 'react'
import TransferTree from '@/components/TransferTree'
import DetailContainer from '@/components/DetailContainer'
import Descriptions from '@/components/Descriptions'
import { Button, message, Space } from 'antd'
import { EditFormInline, EditFormVertical } from '@/components/CustomForm'
import { useFormEdit, useFormSupplier } from './useForm'
import { useForm } from 'antd/es/form/Form'
import { detailRoleById, editRole, getAllRouteTree } from '@/api/role'
import { useSearchParams } from 'react-router-dom'
import './detail.less'
import { getOrgListDetail } from '@/api/org'
import { getProductClassConfigByType } from '@/api/goods'
import { IOptionClass } from '@/pages/Goods/Plan'
const Index: React.FC = () => {
  const [FormEdit] = useForm()
  const [FormSupplier] = useForm()
  const [routeList, setrouteList] = useState<IRoutesType[]>([])
  const [detailInfo, setDetail] = useState<Record<string, any>>({})
  const [menuAuth, setmenuAuth] = useState<string[]>([])
  const [routeAuth, setrouteAuth] = useState<string[]>([])
  const [isBaseEdit, setIsBaseEdit] = useState<boolean>(false)
  const [ispedding, setispedding] = useState<boolean>(false)
  const [desInfoList, setDesInfoList] = useState<IDesListType>([
    {
      label: '组织名称',
      key: 'orgName',
      content: '-',
    },
    { label: '所属应用', key: 'applicationName', content: '-' },
    { label: '角色名称', key: 'roleName', content: '-' },
    { label: '角色描述', key: 'roleDesc', content: '-' },
  ])
  const [supplierOption, setSupplierOption] = useState<IOptionItem[]>([])
  const [isSupplierEdit, setisSupplierEdit] = useState<boolean>(false)
  const [classIdOptions, setclassIdOptions] = useState<IOptionClass[]>([])
  const [query] = useSearchParams()
  const id = query.get('id')
  useEffect(() => {
    getDetail()
    getProductClassConfig()
  }, [])
  const getProductClassConfig = async (type = 1) => {
    const res = await getProductClassConfigByType<{
      className: string
      classConfigId: string | number
    }>({ type, auth: 0 })
    const classIdOptions =
      res?.data?.map((item) => {
        return {
          label: item.className,
          value: item.classConfigId,
        }
      }) || []
    setclassIdOptions(classIdOptions)
  }
  const getDetail = async () => {
    const res = await detailRoleById(id)
    if (res.code === 200) {
      setDetail(res.data)
      getSupList(res.data)
      getAllRoute(res.data)
      const data =
        desInfoList?.map((item) => {
          return {
            ...item,
            content: res.data[item.key] || '-',
          }
        }) || []
      setDesInfoList(data)
      FormSupplier.setFieldsValue({
        supplier: res?.data?.supplier || null,
        classAuthority: res?.data?.classAuthority || null,
      })
      setmenuAuth(res.data.menuAuth || [])
      setrouteAuth(res.data.routeAuth || [])
    }
  }
  const getSupList = async (details: Record<string, any>) => {
    if (details.orgId) {
      const res = await getOrgListDetail<{ supplierPairs: { id: string; name: string }[] }>({ orgIds: [details.orgId] })
      if (res.code === 200) {
        const suppliers = res?.data[0]?.supplierPairs || []
        const supplierOption =
          suppliers?.map((item) => {
            return {
              label: item.name,
              value: item.id,
            }
          }) || []
        setSupplierOption(supplierOption)
      }
    }
  }
  const getAllRoute = async (details: Record<string, any>) => {
    const routes = await getAllRouteTree<IRoutesType>({ applicationId: details.applicationId })
    setrouteList(routes.data)
  }
  const startEdit = () => {
    if (isBaseEdit) {
      FormEdit.validateFields().then(async (data) => {
        const filterData = Object.fromEntries(Object.entries(data)?.filter(([_, val]) => val))
        setispedding(true)
        const res = await editRole({ ...filterData, id, menuAuth, routeAuth }).finally(() => setispedding(false))
        if (res.code === 200) {
          message.success('操作成功')
          setIsBaseEdit(false)
          getDetail()
        }
      })
    } else {
      setIsBaseEdit(true)
      FormEdit.setFieldsValue({
        roleName: detailInfo?.roleName,
        roleDesc: detailInfo?.roleDesc,
      })
    }
  }
  const startEditSupplier = () => {
    if (isSupplierEdit) {
      FormSupplier.validateFields().then(async (data) => {
        setispedding(true)
        const res = await editRole({
          id,
          supplier: data.supplier,
          classAuthority: data.classAuthority ? data.classAuthority : null,
        }).finally(() => setispedding(false))
        if (res.code === 200) {
          message.success('操作成功')
          setisSupplierEdit(false)
          getDetail()
        }
      })
    } else {
      setisSupplierEdit(true)
    }
  }
  const onPowerChange = (menuKey: string[], funcKey: string[]) => {
    setmenuAuth(menuKey)
    setrouteAuth(funcKey)
  }
  const startEditPower = async () => {
    setispedding(true)
    const res = await editRole({ id, menuAuth, routeAuth }).finally(() => setispedding(false))
    if (res.code === 200) {
      message.success('操作成功')
      setIsBaseEdit(false)
      getDetail()
    }
  }
  return (
    <DetailContainer className="role_detail_page">
      <Descriptions
        title="基础信息"
        extra={
          <Space>
            <Button type="primary" onClick={startEdit} loading={ispedding}>
              {isBaseEdit ? '保存修改' : '编辑'}
            </Button>
            {isBaseEdit ? (
              <Button
                onClick={() => {
                  setIsBaseEdit(false)
                  getDetail()
                }}
              >
                取消
              </Button>
            ) : null}
          </Space>
        }
        list={isBaseEdit ? [] : desInfoList}
      >
        <EditFormInline
          editConfig={useFormEdit({
            detailInfo,
          })}
          form={FormEdit}
        />
      </Descriptions>
      <Descriptions
        title="数据权限"
        column={{ xxl: 1, xl: 1, lg: 1, md: 1, sm: 1, xs: 1 }}
        list={
          isSupplierEdit
            ? []
            : [
                {
                  label: '供应商权限',
                  key: '2',
                  content:
                    detailInfo.supplierInfoList?.reduce((acc: string, item: any, index: number) => {
                      return acc + (index === 0 ? '' : ',') + item.supplierName
                    }, '') || '-',
                },
                {
                  label: '大类权限',
                  key: '3',
                  content:
                    detailInfo.classAuthorityList?.reduce((acc: string, item: any, index: number) => {
                      return acc + (index === 0 ? '' : ',') + item.className
                    }, '') || '-',
                },
              ]
        }
        extra={
          <Space>
            <Button type="primary" onClick={startEditSupplier} loading={ispedding}>
              {isSupplierEdit ? '保存修改' : '编辑'}
            </Button>
            {isSupplierEdit ? (
              <Button
                onClick={() => {
                  setisSupplierEdit(false)
                  getDetail()
                }}
              >
                取消
              </Button>
            ) : null}
          </Space>
        }
      >
        <div className="form_out_box">
          <EditFormVertical
            editConfig={useFormSupplier({
              supplierOption,
              isSupplierEdit,
              classIdOptions,
            })}
            form={FormSupplier}
            initialValues={{ supplier: [], classAuthority: [] }}
          />
        </div>
      </Descriptions>
      <Descriptions
        title="功能权限"
        extra={
          <Space>
            <Button type="primary" onClick={startEditPower} loading={ispedding}>
              保存
            </Button>
          </Space>
        }
      >
        <TransferTree
          routeList={routeList}
          onChange={onPowerChange}
          leftKeys={menuAuth}
          rightKeys={routeAuth}
        ></TransferTree>
      </Descriptions>
    </DetailContainer>
  )
}
export default Index
